<template>
	<view class="container">
		<view class="header">
			<view class="center">
				<view class="store">
					<view class="title" @tap="selectLocation">
						<image :src="orderType == 'takein' ?
								'/static/images/common/star_normal.png' :
								'/static/images/order/order_icon_address.png'"
							   class="left-icon" style="margin-top: -0.7rpx"/>
						<!-- 为了测试方便，这里使用静态店铺数据 -->
						<view class="address" style="margin-top: -10rpx">{{  currentShop.zzjgName }}</view>
						<!-- <image style="margin-top: -5rpx;" src="/static/images/common/black_arrow_right.png" class="right-icon"></image> -->
					</view>
					<!-- 外卖&自取switch begin -->
					<view class="buttons">
						<button type="default" class="button"
								:class="{active: orderType == 'takein'}" plain
								hover-class="none" >
							自取
						</button>
<!--						<button type="default" class="button"-->
<!--								:class="{active: orderType == 'takeout'}" plain-->
<!--								hover-class="none" @tap="switchOrderType">-->
<!--							外卖-->
<!--						</button>-->
					</view>
					<!-- 外卖&自取switch end -->
				</view>
				<view  class="location">距离您{{ currentShop.juli}}</view>
			</view>
		</view>

		<view class="phone_info bg-white p-30 d-flex align-items-center justify-content-between mb-20">

			<view>
				<text class="mr-20">联系电话</text>
				<input   v-model="phoneNum"></input>
			</view>
<!--			<button id="btn"  v-trigger open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" type="primary"-->
<!--					plain class="font-size-sm line-height-1" style="border-radius: 20rpx">自动填写</button>-->
		</view>
		<view class="phone_info bg-white p-30 d-flex align-items-center justify-content-between mb-20">

			<view >
				<text class="mr-20">备注</text>
				<textarea bindblur="bindTextAreaBlur" auto-height placeholder="写下你的需求" v-model="mono"/>
			</view>
		</view>
		<view class="phone_info bg-white p-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30">取茶时间</view>
			 <progress percent="10"  stroke-width="10" border-radius="5"/>
			<view class="text-color-primary" style="margin-top: 15rpx;color: black;    letter-spacing: 2rpx;">前面<text class="warn-info" >{{cnum.ocount}}</text>单/<text class="warn-info">{{cnum.ccount}}</text>杯制作中,预计<text class="warn-info">{{cnum.time}}</text>分钟后取茶</view>
			<view class="text-color-primary" style="margin-top: 15rpx;    letter-spacing: 2rpx;
    font-size: 0.7rem;
    color: grey;">正在为您加紧制作中，请耐心等待</view>
		</view>
		<view class="phone_info bg-white pt-30 mb-20">
			<view class="font-size-medium font-weight-bold mb-30 pl-30">商品列表</view>
			<scroll-view scroll-y="true" style="    max-height: 370rpx;">
			<list-cell arrow line-right  v-for="(item, index) in cart" :key="index">
				<view class="w-100 d-flex align-items-center overflow-hidden">
						<view class="d-flex align-items-center">
							<image :src="item.img" class="pro-img"></image>
						</view>
						<view class="w-100">
							<view class="info_title">
								<text>{{item.title}}</text>
							</view>
							<view class="info_spe">
								<text>{{item.materials_text}}</text>
							</view>
						</view>
					<view class="flex-shrink-0 ml-20">共{{ item.number }}件</view>
				</view>
			</list-cell>
			</scroll-view>
			<list-cell last>
				<view class="phone_info w-100 d-flex justify-content-end align-items-center" style="border-radius: 15rpx;">
					<text class="font-size-sm">共{{ cartNum }}件商品，小计</text>
					<text class="font-size-lg font-weight-bold">￥{{ (cartAmount / 100).toFixed(2) }}</text>
				</view>
			</list-cell>
		</view>

		<list-cell last class="phone_info">
			<view class="w-100 d-flex align-items-center justify-content-between phone_info">
				<view>支付方式</view>
				<view class="d-flex align-items-center">
					<image src="/static/images/order/weixin-pay.png" class="wx-pay-icon"></image>
					<view>微信</view>
				</view>
			</view>
		</list-cell>
		<view class="footer">
			<view class="mr-30">
				合计：<text class="font-size-lg font-weight-bold">￥{{ (cartAmount / 100 -couponDiscounts).toFixed(2)*1.0 }}</text>
			</view>
<!--			<button v-if="phoneNum==''||phoneNum==null" type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" @click="payFunc">支付</button>-->
<!--			<button v-if="phoneNum!=''&&phoneNum!=null" type="primary"  @click="payFunc">支付</button>-->

      <button type="primary"  @click="payFunc">支付</button>
		</view>
    <view style="
		        background-color: #ffffff;
		        border-radius: 8px;
		        margin-top: 0.7rem;
		        width: 100wd;
		        overflow: hidden;
		    ">
      <nx-can-use-coupon ref="picCoupon" v-if="couponData.useList.length || couponData.stopList.length"
                         :discounts="couponDiscounts" :isShowCheck="true" :couponData="couponData" @submitCoupon="submitCoupon"
                         :noCouponShow="true"></nx-can-use-coupon>
    </view>
<!--    <view>-->
<!--      <button @click="open1">打开弹窗</button>-->
<!--      <uni-popup ref="popup" type="center">-->
<!--          <p>微信将获取您的手机号以便及时送达您的餐品</p>-->
<!--          <button>确定</button>-->
<!--      </uni-popup>-->
<!--    </view>-->
	</view>

</template>

<script>
	import listCell from '@/components/list-cell/list-cell.vue'

	export default {
		directives:{
			trigger:{
				inserted(el, binging){
					console.log("777777",el.id)
					el.id == 'btn' ? el.click() : null // 只点击第一个，id是在循环中手动添加的
					// $(el).trigger('click')  // 所有都触发一次,然后就是最后一个
				}
			}
		},
		components: {
			listCell
		},
		data() {
			return {
        flag_pay_action:false,
				categoryListRecord:[],
			  couponId:'',
        searchQuery: {type:0},
        couponDiscounts: 0,
        couponData: {
          useList:[],
          stopList: []
        },
				cnum:{
					ocount:11,
					ccount:11,
					time:0
				},
				currentShop:{},
				cart: uni.getStorageSync('cart'),
				phone: "",
				zzjgId: 1,
				phoneNum:"",
				tryFlag:1,
				mono:'',
        currentOrderNo:''
			}
		},
		onLoad(option){
      this.$bus.$on('couponChecked', this.couponChecked)
			console.log("cart",this.cart)
			this.currentShop  = JSON.parse(decodeURIComponent(option.shop));
			this.zzjgId = this.currentShop.zzjgid
			console.log("aaa",this.currentShop)
			uni.login({
				success:res=>{
					uni.setStorageSync("wxcode",res.code)
				}
			})
		},
    async onShow(){
      let that = this

      let coupons = await this.getCouponListByUser();
	     console.log("coupons",coupons)
      this.couponData.useList = coupons.filter((item=>{ //如果该优惠卷的最小使用金额小于支付金额就把它加入可用列表
                let {typeShop}  = item
                if(typeShop ===3){
                      return this.canUserCategroyCoupon(item.categoryId,item.categoryTitle,item.type)
	              }else if(typeShop ===2){
                  return item.min*100<=this.cartAmount&&this.cartNum<=1;
                }
                return item.min*100<=this.cartAmount
        //return true;
      }))
      this.couponData.stopList = coupons.filter((item=>{  //如果该优惠卷的最小使用金额小于支付金额就把它加入可用列表
          let {typeShop}  = item
          if(typeShop ===3){
            return !this.canUserCategroyCoupon(item.categoryId,item.categoryTitle,item.type)
          }else if(typeShop ===2){ //处理折扣卷需要限定一件商品
              return item.min*100>this.cartAmount||this.cartNum>1;
          }
         return item.min*100>this.cartAmount
      }))
      // 赋值且给checkbox给默认值
      this.couponData.useList = this.couponData.useList.map((item) => {
        let obj = {
          ...item,
          checked: false, // 勾选
          topRightTip: false, //右上角提示
          bottomTip: false // 底部提示
        }
        return obj
      })
      console.log('this.couponData.useList', this.couponData.useList)
      if (this.$refs.picCoupon) {
        this.$refs.picCoupon.setUseData(that.couponData.useList)
        this.$refs.picCoupon.setStopList(that.couponData.stopList)
      }


    },
		computed: {
			cartNum() {
				return this.cart.reduce((acc, cur) => acc + cur.number, 0)
			},
			cartAmount() {
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
			},
			remark() {
				return this.$store.state.remark
			}
		},
		mounted() {
        this.phone = uni.getStorageSync("phone");
			this.phoneNum = uni.getStorageSync("phone");
			this.getCookNum()
	
		},
		methods: {
      open1(){
        this.$refs.popup.open('top')
      },
      /**
       *
       * @param ttcategoryId   优惠卷指定的商品类别
       * @param ttTitle        优惠卷指定的商品类别名称
       * @param ttType         优惠卷类型（0 平台卷  1 店铺卷
       * @returns {boolean}
       */
			canUserCategroyCoupon(ttcategoryId,ttTitle,ttType){
        let cart = uni.getStorageSync("cart");
        if(ttType == 1) {
          for (let item of cart) {
            let {categoryId} = item;
            if (categoryId !== ttcategoryId) {
              return false;
            }
          }
          return true;
        }else{
          /**
           *             说明是平台的免费卷
           *             对于平台的免费卷我们要看当前先的商品所属类目是否跟平台所选类目名称一致
           */
          for (let item of cart) {
            let {categoryFullNames,number} = item;
            if (categoryFullNames !== ttTitle||number>1) {
              return false;
            }
          }
          return true;
        }
			},
      submitCoupon(coupons){
        this.couponId = '';
        this.couponDiscounts = 0;
		    console.log("coupons",coupons)
        //目前不支持优惠卷叠加故每次只可能有一个优惠卷
        coupons.forEach(item=>{
            let {id,discount,typeShop} = item
              this.couponId = id
            if(typeShop === 1){
              this.couponDiscounts = discount
            }else if(typeShop ===2){
              this.couponDiscounts =  ((this.cartAmount / 100)*((1-(discount/10)).toFixed(2))).toFixed(2)
            }else if (typeShop ===3){
              /**
               * 因为只能优惠一件所以
               * @type {number}
               */
              this.couponDiscounts  = (this.cartAmount / 100).toFixed(2)*1.0-0.01
            }
		  
        })
        console.log("eee",this.couponDiscounts)
      },
			getCookNum (){
				this.$api.ajax({
					url: "/web/app-order/get-order-in-cook-count",
					// method: "post",
					data: {
						zzjgId:this.zzjgId,
						userId: uni.getStorageSync("userId")
					},
					success: (res) => {
						const { data } = res.data || {};
						const { items } = data || {};
						if(data!=null&&data.length>0){
							this.cnum = data[0]
							let yunying = Math.floor((Math.random()*3)+1)
							this.cnum.ocount = this.cnum.ocount+yunying
							this.cnum.ccount = this.cnum.ccount+yunying
							if(this.cnum.ccount>5){
								this.cnum.ccount = 5
								this.cnum.ocount = 5
							}
							this.cnum.time = this.cnum.ccount*2
						}
						console.log("abc",data)
					}
				});
			},
			getPhoneNumber(e){
				console.log("你是好的")
				var ivObj = e.detail.iv
				var telObj = e.detail.encryptedData
				var codeObj = "";
				var that = this;
				this.tryFlag = 0;
				this.wget(ivObj,telObj)


			},
			wget(ivObj,telObj){
				//------执行Login---------
				wx.login({
					success: res => {
						console.log('code转换', res.code);
						this.$api.ajax({
							url: "/wx/lite/n/code-get-phonenum",
							data: {
								// appid: this.commonData.appId,
								// secret: this.commonData.secret,
								loginType: 1,
								ip: "127.0.0.1",
								js_code: res.code,
								ivObj:ivObj,
								telObj:telObj,
                brandType:this.$api.brandId,
								// js_code: wxres.code
							},
							success: (res) => {
								try{
									this.tryFlag++
									this.phoneNum = JSON.parse(res.data.data).phoneNumber
									this.updateUserPhone(this.phoneNum)
                  if(this.flag_pay_action){ //从支付方法触发的情况下 立马再进行支付
                    this.payFunc()
                    this.flag_pay_action = false;
                  }
								}catch (e) {
									if(this.tryFlag<2){
										this.wget(ivObj,telObj)
									}else{
										console.log(e)
									}
								}
							}
						})
					}
				})
			},
			updateUserPhone(pNum){
				let us = JSON.stringify({phone:pNum,id:uni.getStorageSync("userId"),brandType:this.$api.brandId});
				this.$api.ajax({
					url: "/web/app-user/edit",
					data:us,
					method: "post",
					header: {
						"Content-Type": "application/json;charset=utf-8"
					},
					success:(res)=> {
						// console.log(res);
						const { data } = res.data || {};
						console.log("data",data);

					}
				});

			},
			payFunc() {

        console.log("aaa",uni.getStorageSync("phone"))
        //自动获取手机号服务关闭
        // if(this.phoneNum == ''||this.phoneNum == null|| this.phoneNum ==undefined){
        //   this.flag_pay_action = true;//在支付环节如果用户手机号为空的话，做下标记，这样自动获取用户手机号后会马上进行支付动作
        //   return;
        // }
				// /web/coldOrder/createOrder
				let cart = uni.getStorageSync("cart");
				let total = this.cartAmount;
				let skuList = [];

				skuList = cart.map(item => {
					this.zzjgId = item.zzjgId
					return {
						barCode: new Date().getTime(),
								title: item.title,
								specification: item.materials_text,
								originalPrice: item.price,
								vipPrice: item.price,
								price: item.price,
								spuId: item.id,
							 num: item.number
					};
				});
				console.log("yp",this.zzjgId)

				let param = {
					channel: "online",
					userId: uni.getStorageSync("userId"),
					zzjgId:this.zzjgId,
					orderRequest: JSON.stringify({
						skuList,
						totalPrice: total,
						totalOriginalPrice: total,
						addressId: "111",
						groupShopId: null,
						couponId: this.couponId,
						mono: this.mono,
						takeWay: "cart",
						freightPrice: 0,
						exceptPrice: total-this.couponDiscounts*100,
						isVirtual: true,
						phoneNum:this.phoneNum
					}),
					isBaiHuo: 0
				};

				const that = this;
				uni.showLoading({
					title: '加载中...'
				});
				this.$api.ajax({
					url: "/web/app-order/take-order",
					data: param,
					method: "post",
					header: {
						"Content-Type": "application/x-www-form-urlencoded"
					},
					success:(res)=> {
						const { data,code,attach } = res.data || {};
            console.log("dddd11",res);
            if(code===13003){ //说明没有库存了
              /***
               * :
               expect: 1
               skuId: "1469564279165349890"
               surplus:
               */
              var infoStr = "饮品抢光了,看看\n别的饮品吧\n";
              if(attach) {
                attach.forEach(item => {
                  let {expect, skuId, surplus, spuTitle} = item;
                  infoStr += "饮品" + spuTitle + "抢光了,看看\n别的饮品吧\n"
                })
              }
              that.$api.msg(infoStr,3000);
            }

            // 订单的id
						// data
						if (data) {
							let parentOrderNo = data;
              that.currentOrderNo = data;
							that.$api.ajax({
								url: "/web/app-order/wx-prepay",
								data: {
									orderNo: "",
									parentOrderNo: parentOrderNo,
									ip: "192.168.30.111",
									zzjgId: this.zzjgId,
									userId: uni.getStorageSync("userId")
								},
								method: "post",
								header: {
									"Content-Type": "application/x-www-form-urlencoded"
								},
								success(res) {
									const { data } = res.data || {};
									const { appId, nonceStr, packageValue, paySign, signType, timeStamp } = data || {};
                                     console.log("OrderInfo",data)
									wx.requestPayment(
									{
									"timeStamp": timeStamp,
									"nonceStr": nonceStr,
									"package": packageValue,
									"signType": signType,
									"paySign": paySign,
									'success':function(res){
										wx.requestSubscribeMessage({tmplIds:["jHiWM7_QWaa-zZc6LPpcR1GLIunMcS7sDuLqJo-vXTU","4rmQ2k5SfYncpijWA04m2bmhav4xahmD449u_c6XH20","_RTAcVFKZ-ReMN1AvS-g00zPmkCPmK_vf2v8x4V-vaM"],success:()=>{
											console.log("1");
										  },fail:(f)=>{
											console.log("2",f);
										  },complete:()=>{
											console.log("3");
                        that.notyUser()
										  }})
										that.$api.msg("支付成功");
										
										
										
										
										
										uni.removeStorageSync("cart")
										// uni.reLaunch({
										// 	url: '/pages/order/order?flag=adview'
										// })
                    ///pages/order/detail?id=' + order.id
                    uni.navigateTo({
                      url: '/pages/order/detail?orderNo=' + parentOrderNo

                    })

									},
									'fail':function(res){
										that.$api.msg("支付失败");
										console.log(res, 198);
									},
									'complete':function(res){
										console.log(res, 201)
									}
									})
								},
								complete() {
									uni.hideLoading();
								}
							});
						}

					},
          complete:(res)=>{
            uni.hideLoading();
          }
				});
			},
      notyUser(){
        this.$api.ajax({
          url: "/web/app-order/send-noty",
          data: {
            templateId: "jHiWM7_QWaa-zZc6LPpcR1GLIunMcS7sDuLqJo-vXTU",
            orderNo: this.currentOrderNo,
            zzjgId: this.zzjgId,
            openId: uni.getStorageSync("openId"),
            brandId: this.$api.brandId,
            page: 'index'
          },
          method: "post",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          success(res) {
            const { data } = res.data || {};
            console.log("OrderInfo",data)
          },
          complete() {
          }
        });
      },
      setCheckUseList(parameIndex, setBool, isAdd) {
        // isAdd是否可叠加 0 不可叠加 1 可叠加 2 所有 其他参数见下
        let that = this
        let tempArray = []
        that.couponData.useList.forEach((item, index) => {
          let obj = item
          let isAddBool = true
          if (isAdd == 0) {
            isAddBool = item.isAdditivity == 0 ? true : false
          } else if (isAdd == 1) {
            isAddBool = item.isAdditivity == 1
          }
          if (parameIndex != index && isAddBool) {
            obj.checked = setBool
          }

          tempArray.push(obj)
        })
        that.couponData.useList = tempArray
        if (this.$refs.picCoupon) {
          this.$refs.picCoupon.setUseData(tempArray)
        }
      },
      setDefaultUseList(parameIndex, topOrBot, setBool, isAdd) {
        // index, -1所有还是其他索引，topOrBoT（0：top，1:bot 2 二个都有 ）顶部或者底部的提示，setBool设置值成true或者false,isAdd是否可叠加 0 不可叠加 1 可叠加 2 所有
        let that = this
        // console.log('parameIndex', parameIndex);
        // console.log('topOrBot', topOrBot);
        // console.log('setBool', setBool);
        // console.log('isAdd', isAdd);
        let tempArray = []
        that.couponData.useList.forEach((item, index) => {
          let obj = item
          let isAddBool = true
          if (isAdd == 0) {
            isAddBool = item.isAdditivity == 0 ? true : false
          } else if (isAdd == 1) {
            isAddBool = item.isAdditivity == 1
          }
          if (parameIndex != index && isAddBool) {
            if (topOrBot == 0) {
              obj.topRightTip = setBool
            } else if (topOrBot == 1) {
              obj.bottomTip = setBool
            } else {
              obj.topRightTip = setBool
              obj.bottomTip = setBool
            }
          }

          tempArray.push(obj)
        })
        that.couponData.useList = tempArray
        if (this.$refs.picCoupon) {
          this.$refs.picCoupon.setUseData(tempArray)
        }
      },
      couponChecked(index) {
			  console.log('总金额',this.cartAmount)
        let that = this
        console.log('index', index)
        console.log(
            'that.couponData.useList[index]',
            that.couponData.useList[index]
        )

        that.couponData.useList[index].checked = !that.couponData.useList[index].checked
        if (that.couponData.useList[index].checked) {
          // 勾选上
          console.log('勾选上')

          // 把自己的底部提示隐藏起来
          that.couponData.useList[index].bottomTip = false
          this.$refs.picCoupon.setUseData(that.couponData.useList)
          let isAdditivity = that.couponData.useList[index].isAdditivity // 勾选的是否可叠加
          if (isAdditivity) {
            // 可叠加
            console.log('可叠加')
            // 把所有不可以叠加的优惠券取消勾选
            that.setCheckUseList(-1, false, 0)
            // 把所有可以叠加的优惠券右上角提示显示出来
            that.setDefaultUseList(-1, 0, true, 1)
            // 把所有不可以叠加的优惠券底部提示显示出来
            that.setDefaultUseList(-1, 1, true, 0)
            // 把所有可以叠加的优惠券底部提示隐藏起来
            that.setDefaultUseList(-1, 1, false, 1)
          } else {
            // 不可叠加
            console.log('不可叠加')
            // 把其他所有优惠券取消勾选
            console.log('把其他所有优惠券取消勾选')
            that.setCheckUseList(index, false, 2)
            // 把所有可以叠加的优惠券右上角提示隐藏起来
            that.setDefaultUseList(-1, 0, false, 1)
            // 把其他所有优惠券底部提示显示出来
            that.setDefaultUseList(index, 1, true, 2)
          }
        } else {
          // 取消勾选
          console.log('取消勾选')
          let isAdditivity = that.couponData.useList[index].isAdditivity // 取消的是否可叠加
          if (isAdditivity) {
            // 可叠加
            let checkList = that.couponData.useList.map(
                (item) => item.checked
            ) // 获取所有勾选的优惠券
            if (checkList.length == 0) {
              // 没有勾选的可叠加优惠券
              //去掉所有提示
              that.setDefaultUseList(-1, 2, false, 2)
            }
          } else {
            // 不可叠加
            //去掉所有提示
            that.setDefaultUseList(-1, 2, false, 2)
          }
        }
      },
       getCouponListByUser(){
			  return new Promise(resolve => {
          this.$api.ajax({
            url: "/web/app-coupon/list",
            data: {
              userId: uni.getStorageSync("userId"),
              status: this.searchQuery.type,
			        zzjgId: this.zzjgId
            },
            method: "post",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success:(res) =>{
              const { data } = res.data || {};
              console.log(data)
              this.couponList = data;
              resolve(data)
              uni.hideLoading();

            }
          });
        })

      },
		}
	}
</script>

<style lang="scss" scoped>
	@import '../index/index.scss';

	.container{
		width: 95%;
		margin: 15rpx auto;
		border-radius: 15rpx;
		.info_title{
			margin-bottom: 15rpx;

		}
		.warn-info{
			font-size: 1.1rem;
			color: orange;

		}
		list-cell{
			view{
				border-radius: 15rpx;;
			}
		}
		background-color: transparent!important;
		.header{
			background-color: white;
			border-radius: 15rpx;
			margin-bottom: 15rpx;
			.store{
				.buttons{
					.button{
						width: 100%;
					}
				}

			}
		}
		.phone_info{
			border-radius: 15rpx;
			input{
				display: block;
				float: right;
				background-color: whitesmoke;
				border-radius: 3px;
				margin-top: -2px;
			}
		}
		.center{
			.location{
				margin-left: -0.4rem;
			}
			.store{
				.title{
					margin-left: -0.8rem;
				}
			}
		}
	}
	.pro-img {
		width: 140rpx;
		height: 140rpx;
		flex-shrink: 0;
	}

	.coupon-label {
		background-color: $color-primary;
		color: #FFFFFF;
		font-size: 18rpx;
		line-height: 0.9rem;
		width: 0.9rem;
		height: 0.9rem;
		margin-left: 10rpx;
		text-align: center;
	}

	.wx-pay-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	.footer {
		background-color: #FFFFFF;
		z-index: 10;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;

		button {
			width: 250rpx;
			text-align: center;
			padding: 0;
			height: 100%;
			line-height: 100rpx;
			border-radius: 0 !important;
			font-size: $font-size-lg;
		}
	}
</style>
